import Taro from '@tarojs/taro'

import { showToast } from '../utils'

const baseUrl = process.env.NODE_ENV === 'production' ? 'https://erp.webapi.cl-zenith.com' : 'https://erp.webapi.testing.cl-zenith.com'

export default async ({url, method = 'GET', data}) => {
  const pages = Taro.getCurrentPages()
  const currentPath = pages[pages.length - 1].route
  let token = ''

  const toLogin = () => {
    showToast('请登录！')

    setTimeout(() => {
      Taro.clearStorage()
      Taro.navigateTo({
        url: '/pages/login/index'
      })
    }, 1000)
  }

  if (!currentPath.includes('login')) {
    token = await Taro.getStorage({
      key: 'token',
      fail: () => {
        toLogin()
      }
    })
  }

  return new Promise((resolve, reject) => {
    Taro.request({
      header: { Authorization: token.data },
      url: baseUrl + url,
      method,
      data
    }).then(({ data }) => {
      if (data.code === -999) {
        toLogin()
        return
      }
      resolve(data)
    }).catch(err => {
      reject(err)
    })
  })
}